package com.simoniu.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

//设计为一个单例模式，获得数据库的连接对象。
public class DBUtil {

    //懒汉模式
    private static Connection conn = null; //数据库的连接对象
    private static String url =null; //数据库的URL
    private static String username = null; //数据库的用户名
    private static String password = null; //数据库的密码

    //构造方法必须私有
    private DBUtil(){

    }

    static{
        //加载驱动
        try{
            Properties properties = new Properties();
            properties.load(DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            String driverClassName = properties.getProperty("driverClassName");
            //加载驱动
            Class.forName(driverClassName);
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");

        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    public static Connection getConnection() throws Exception{
        if(conn==null || conn.isClosed()){
            conn = DriverManager.getConnection(url,username,password);
        }
        return conn;
    }
}
